﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GanagroLiteBO;
using System.Globalization;
using GeneralUtilities;

namespace GanagroLite
{
    public partial class FormCompras : FormOperaciones
    {
        private ModoForma mForma = ModoForma.inicializando;
        OpArgs cArgs = new OpArgs(TiposOperacion.compra);
        private bool _modoConsulta = false;
        private int  OriginalColWidth;

        #region Constructor

        public FormCompras(bool modoConsulta)
        {
            InitializeComponent();
            this.bindingSourceMain.DataSource = new Compras();
            currentNota = new NotaBO(TiposOperacion.compra);
            this.bindingSourceNota.DataSource = currentNota;
            this.btnGuardar.Enabled = false;
            this.dataGridViewMain.Enabled = false;
            _modoConsulta = modoConsulta;
            OriginalColWidth = dataGridViewMain.Width;
        }
       
        #endregion

        #region Internal methods

        protected internal override object GetIdValue()
        {
            return "Comprar Semovientes";
        }

        public override string ToString()
        {
            return "Comprar Semovientes";
        }

        #endregion

        #region bindingSource Events

        private void bindingSourceMain_AddingNew(object sender, AddingNewEventArgs e)
        {
            Int32 precioKilo = 0;
            NumberStyles styles = NumberStyles.Integer | NumberStyles.AllowThousands;
            Int32.TryParse(this.textBoxPrecio.Text, styles, CultureInfo.InvariantCulture, out precioKilo);

            cArgs.Finca = "1";
            cArgs.Lote = Convert.ToByte(this.cboLote.SelectedValue);
            cArgs.Marca = this.textBoxMarca.Text;
            cArgs.Sexo = "M";
            cArgs.Alojo = this.rbAlOjo.Checked;
            cArgs.ValorKilo = precioKilo;
            cArgs.Estado = (byte)Estados.ceba;

            Int32 edad;
            Int32.TryParse(this.textBoxEdad.Text, out edad);
            cArgs.Edad = edad;

            Compras C = (Compras)this.bindingSourceMain.DataSource;
            List<string> nuevoscodigos = (from p in C select p.CODIGO).ToList<string>();
            e.NewObject = new CompraBO(nuevoscodigos, cArgs, currentNota);
        }

        private void bindingSourceMain_PositionChanged(object sender, EventArgs e)
        {
            btnGuardar.Enabled = (_modoConsulta == false) && currentNota.Isvalid(true) && (bindingSourceMain.Count>0);
        }

        #endregion

        #region UI Handlers

        private void FormCompras_Load(object sender, EventArgs e)
        {
            this.cboLote.DataSource = UtilityDB.Loadlotes();
            this.cboLote.ValueMember = "ID";
            this.cboLote.DisplayMember = "DESCRIPCION";

            cboLote.SelectedValue = 7;
            this.textBoxEdad.Text = "18";

            mForma = ModoForma.cargada;

        }

        private void dtPickerFecha_Validated(object sender, EventArgs e)
        {
            try
            {
                currentNota.Fecha = Convert.ToDateTime(dtPickerFecha.Text).Date;
                currentNota.Cargar();

                this.errorProviderNotasFecha.SetError(dtPickerFecha, currentNota.Error);
                this.WarningProviderNotas.SetError(dtPickerFecha, currentNota.Warnings());

                btnGuardar.Enabled = (_modoConsulta == false) && currentNota.Isvalid(true) && (bindingSourceMain.Count > 0);

                if (this.bindingSourceMain.Count > 0)
                {
                    ((Compras)this.bindingSourceMain.DataSource).Setfecha(Convert.ToDateTime(dtPickerFecha.Text));
                }

                bindingSourceMain.ResetBindings(false);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void rbAlOjo_CheckedChanged(object sender, EventArgs e)
        {
            if (mForma == ModoForma.cargada)
                this.bindingSourceMain.ResetBindings(true);

            if (rbAlOjo.Checked)
            {
                dataGridViewMain.Columns[dataGridViewMain.ColumnCount - 1].Visible = false;
                dataGridViewMain.Width = 120;

                currentNota.Alojo = true;
                currentNota.Isvalid(false);
                bindingSourceNota.ResetBindings(false);

                if (this.bindingSourceMain.Count > 0)
                    ((Compras)this.bindingSourceMain.DataSource).SetAlojo(true);

                NumberStyles styles = NumberStyles.Integer | NumberStyles.AllowThousands;
                Int32 precioKilo;
                if (Int32.TryParse(this.textBoxPrecio.Text, styles, CultureInfo.InvariantCulture, out precioKilo))
                {
                    currentNota.Precio = precioKilo;
                }
            }

        }

        private void rbPeso_CheckedChanged(object sender, EventArgs e)
        {
            if (mForma == ModoForma.cargada)
                this.bindingSourceMain.ResetBindings(true);
            
            if (rbPeso.Checked)
            {
  //              this.textBoxPrecio.Enabled = true;
                dataGridViewMain.Columns[dataGridViewMain.ColumnCount - 1].Visible = true;
                dataGridViewMain.Width = OriginalColWidth;

                currentNota.Alojo = false;
                currentNota.Isvalid(false);
                bindingSourceNota.ResetBindings(false);

                if( this.bindingSourceMain.Count > 0 )
                ((Compras)this.bindingSourceMain.DataSource).SetAlojo(false);

            }
        }

        private void buttonNota_Click(object sender, EventArgs e)
        {
            GuardarNota(); 
        }

        private void textBoxPrecio_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && e.KeyChar != 8)
            {
                // Consume this invalid key and beep
                e.Handled = true;
            }
        }

        private void textBoxEdad_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) & e.KeyChar != 8 )
            {
                // Consume this invalid key and beep
                e.Handled = true;
            }
        }

        private void textBoxPrecio_Validated(object sender, EventArgs e)
        {
            try
            {
                btnGuardar.Enabled = (_modoConsulta == false) && currentNota.Isvalid(false) && (bindingSourceMain.Count > 0);
                short precio = 0;
                NumberStyles styles = NumberStyles.Integer | NumberStyles.AllowThousands;
                short.TryParse(this.textBoxPrecio.Text, styles, CultureInfo.InvariantCulture, out precio);

                this.dataGridViewMain.Enabled = precio > 0;
                if (this.bindingSourceMain.Count > 0)
                {
                    {
                        ((Compras)this.bindingSourceMain.DataSource).Setprecio(precio);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void textBoxEdad_TextChanged(object sender, EventArgs e)
        {
            if (this.bindingSourceMain.Count > 0)
            {
                short edadMeses = 0;
                short.TryParse(this.textBoxEdad.Text, out edadMeses);
                ((Compras)this.bindingSourceMain.DataSource).SetEdad(edadMeses);
            }

        }

        private void textBoxMarca_TextChanged(object sender, EventArgs e)
        {
            if (this.bindingSourceMain.Count > 0)
            {
                ((Compras)this.bindingSourceMain.DataSource).SetMarca(this.textBoxMarca.Text);
            }

        }

        private void textBoxNota_TextChanged(object sender, EventArgs e)
        {
            buttonNota.Enabled = !string.IsNullOrEmpty(textBoxNota.Text);
            btnGuardar.Enabled = (_modoConsulta == false) && currentNota.Isvalid(true) && (bindingSourceMain.Count > 0);
        }

        private void cboLote_SelectedValueChanged(object sender, EventArgs e)
        {
            if (mForma == ModoForma.cargada)
            {
                if (this.bindingSourceMain.Count > 0)
                {
                    ((Compras)this.bindingSourceMain.DataSource).SetLote(byte.Parse(cboLote.SelectedValue.ToString()));
                }

            }

        }

        private void btnGuardar_Click_1(object sender, EventArgs e)
        {
            VGuardar<CompraBO>(this,this.bindingSourceMain,false); 
        }

        private void buttonSalir_Click(object sender, EventArgs e)
        {
            if (confirmaSalir(bindingSourceMain.Count) == false)
            { return ; }

            this.bindingSourceNota.CancelEdit();
            this.bindingSourceMain.CancelEdit();
            this.status = string.Empty;

            this.Close();
        }  

        private void dataGridViewMain_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            try
            {
                MessageBox.Show("Valor en formato Invalido");
            }
            catch (Exception)
            {
                MessageBox.Show("Valor en formato Invalido");
            }

        }

        private void textBoxNota_Validated(object sender, EventArgs e)
        {
            btnGuardar.Enabled = (_modoConsulta == false) && currentNota.Isvalid() && (bindingSourceMain.Count > 0);
        }

        private void dataGridViewMain_DataError_1(object sender, DataGridViewDataErrorEventArgs e)
        {
            MessageBox.Show("Valor en formato Invalido");
        }

        #endregion

        private void dtPickerFecha_Validating(object sender, CancelEventArgs e)
        {
            DateTime dt;

            this.errorProviderNotasFecha.SetError(dtPickerFecha, string.Empty);

            if (DateTime.TryParse(dtPickerFecha.Text, out dt) == false)
            {
                this.errorProviderNotasFecha.SetError(dtPickerFecha, "Formato de fecha invalido");
                e.Cancel = true;
            }

            if (dt > DateTime.Now)
            {
                this.errorProviderNotasFecha.SetError(dtPickerFecha, "La fecha no puede ser en el futuro");
                e.Cancel = true;
            }
        }

        private void bindingSourceMain_CurrentItemChanged(object sender, EventArgs e)
        {
            this.lblCabezas.Text = ((Compras)this.bindingSourceMain.DataSource).Count().ToString();
            this.lblProm.Text = String.Format("{0:0.0}",((Compras)this.bindingSourceMain.DataSource).Where(wp => wp.Peso > 0).Average(wp => wp.Peso));
        }
    }
}
